"use strict";

const Controller = require("egg").Controller;

class HomeController extends Controller {
  async index() {
    const { ctx, app } = this;
    ctx.body = {
      code: 200,
      data: await app.mysql.select("allarticles"),
    };
  }
  async del(){
    const { ctx, app } = this;
    const {id}=ctx.query
    const result=await app.mysql.delete("allarticles",{id})
    if(result.affectedRows){
      ctx.body={
        code:200,
        data:await app.mysql.select("allarticles")
      }
    }
  }
  async classifyList(){
    const { ctx, app } = this;
    const data=await app.mysql.select("labels")
    let newobj={}
    //过滤数据 筛选出分类名称不同的对象
    const a=data.reduce((pre,cur)=>{
        newobj[cur.classname]?"":newobj[cur.classname]=pre.push(cur)
        return pre
    },[])
    ctx.body={
      code:200,
      data:a
    }
  }
  async addClassify(){
    const {ctx,app}=this
    const {name,value}=ctx.request.body
    const result=await app.mysql.get("labels",{classname:name,measure:value})
    if(result){
      ctx.body={
        code:504,
        mess:"数据存在，请修改"
      }
    }else{
      let data=await app.mysql.insert("labels",{
        classname:name,
        measure:value,
        id:null
      })
      if(data.affectedRows){
        ctx.body={
          code:200,
          data:await app.mysql.select("labels")
        }
      }
    }
  }
  async findClassify(){
    const {ctx,app}=this
    const {id}=ctx.request.body
    const data=await app.mysql.get("labels",{id})
    if(data){
      ctx.body={
        code:200,
        data:data
      }
    }
  }
  async allDel(){
    const {ctx,app}=this
    const {arr}=ctx.request.body
    arr.forEach(async(item)=>{
      await app.mysql.delete("allarticles",{id:item.id})
    })
    ctx.body={
      code:200,
      mess:"批量删除成功",
      data:await app.mysql.select("allarticles")
    }
  }
}

module.exports = HomeController;
